package server

import (
	"errors"
	"fmt"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"go_self/model"
	"go_self/util"
	"strings"
	"time"
)

// UserShoppingCartByAdd 添加购物车
func UserShoppingCartByAdd(userId int64, skuId string, number string) error {

	timeString := time.Now().Format(time.RFC3339)
	userShoppingCartSql, args := sql_aid.PgTable(model.TableByUserShoppingCart).Where("user_id = ?", userId).Where("goods_sku_id = ?", skuId).ToSql()
	userShoppingCartData, err := sql_aid.DataToMap(model.PgSql.Query(userShoppingCartSql, args...))
	if err != nil {
		return err
	}
	if userShoppingCartData != nil {
		//执行增加
		update := make(map[string]interface{})
		update["time_u"] = timeString
		sql, args := sql_aid.PgTable(model.TableByUserShoppingCart).WhereId(userShoppingCartData[0]["id"]).Inc("number", number).UpdateByMap(&update)
		_, err = model.PgSql.Exec(sql, args...)
	} else {
		//查询商品
		goodsSkuSql, args := sql_aid.PgTable(model.TableByGoodsSku).WhereId(skuId).ToSql()
		goodsSkuSqlData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSkuSql, args...))
		if err != nil {
			return err
		}
		if len(goodsSkuSqlData) == 0 {
			return errors.New("skuId=" + skuId + "的商品不存在")
		}
		insert := make(map[string]interface{})
		insert["user_id"] = userId
		insert["shop_id"] = goodsSkuSqlData[0]["shop_id"]
		insert["goods_id"] = goodsSkuSqlData[0]["goods_id"]
		insert["goods_sku_id"] = goodsSkuSqlData[0]["id"]
		insert["number"] = number
		insert["price"] = goodsSkuSqlData[0]["price"]
		insert["time_c"] = timeString
		insert["time_u"] = timeString
		sql, args := sql_aid.PgTable(model.TableByUserShoppingCart).InsertByMap(&insert)
		_, err = model.PgSql.Exec(sql, args...)
		if err != nil {
			return err
		}
	}
	if err != nil {
		return err
	}
	return nil
}

// UserShoppingCartByList 购物车列表
func UserShoppingCartByList(userId int64) []map[string]interface{} {
	userShoppingCartSql, arge := sql_aid.PgTable(model.TableByUserShoppingCart).Where("user_id = ?", userId).ToSql()
	userShoppingCartData, err := sql_aid.DataToMap(model.PgSql.Query(userShoppingCartSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserShoppingCartByList", "购物车列表", err.Error())
		return nil
	}
	if len(userShoppingCartData) == 0 {
		return nil
	}
	//店铺信息
	shopIds := util.ArrayField(&userShoppingCartData, "shop_id")
	shopSql, arge := sql_aid.PgTable(model.TableByShop).Field("id", "title", "logo", "status").WhereIn("id", *shopIds...).ToSql()
	shopData, err := sql_aid.DataToMap(model.PgSql.Query(shopSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserShoppingCartByList", "店铺信息错误", err.Error())
		return nil
	}
	//商品信息
	goodsIds := util.ArrayField(&userShoppingCartData, "goods_id")
	goodsSql, arge := sql_aid.PgTable(model.TableByGoods).Field("id", "title", "picture", "up_down").WhereIn("id", *goodsIds...).ToSql()
	goodsData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserShoppingCartByList", "商品信息错误", err.Error())
		return nil
	}
	//sku信息
	goodsSkuIds := util.ArrayField(&userShoppingCartData, "goods_sku_id")
	goodsSkuSql, arge := sql_aid.PgTable(model.TableByGoodsSku).Field("id", "goods_id", "price", "picture", "sku_string").WhereIn("id", *goodsSkuIds...).ToSql()
	goodsSkuData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSkuSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserShoppingCartByList", "sku信息错误", err.Error())
		return nil
	}

	goodsSkuDataByColumnGoodsId := util.ArrayColumnByInt64(&goodsSkuData, "id")
	goodsDataByColumnGoodsId := util.ArrayColumnByInt64(&goodsData, "id")
	for _, carVal := range userShoppingCartData {
		if goodsSkuDataByColumnGoodsId[carVal["goods_sku_id"].(int64)] != nil {
			carVal["sku"] = goodsSkuDataByColumnGoodsId[carVal["goods_sku_id"].(int64)]
		} else {
			carVal["sku"] = nil
		}
		if goodsDataByColumnGoodsId[carVal["goods_id"].(int64)] != nil {
			carVal["goods"] = goodsDataByColumnGoodsId[carVal["goods_id"].(int64)]
		} else {
			carVal["goods"] = nil
		}
	}
	shoppingCartDataByColumnShopId := util.ArrayColumnGroupByInt64(&userShoppingCartData, "shop_id")
	for _, shopVal := range shopData {
		if shoppingCartDataByColumnShopId[shopVal["id"].(int64)] != nil {
			shopVal["goods"] = shoppingCartDataByColumnShopId[shopVal["id"].(int64)]
		}
	}

	return shopData
}

// UserShoppingCrtByDel 删除购物车中的商品
func UserShoppingCrtByDel(userId int64, ids string) error {
	goodsIdsBySplitString := strings.Split(ids, ",")
	goodsIdsBySplitInterface := make([]interface{}, 0)
	for _, val := range goodsIdsBySplitString {
		goodsIdsBySplitInterface = append(goodsIdsBySplitInterface, val)
	}
	shoppingCart, args := sql_aid.PgTable(model.TableByUserShoppingCart).WhereIn("id", goodsIdsBySplitInterface...).Where("user_id = ?", userId).Delete()
	fmt.Println(shoppingCart, args)
	_, err := model.PgSql.Exec(shoppingCart, args...)
	if err != nil {
		gogo_log.Error("server_UserShoppingCrtByDel", "购物车删除商品失败", err.Error())
		return errors.New("删除失败")
	}
	return nil
}

// UserShoppingCrtByEditNumber 增加购物车的商品数量
func UserShoppingCrtByEditNumber(userId int64, ids string, number string) error {
	goodsIdsBySplitString := strings.Split(ids, ",")
	goodsIdsBySplitInterface := make([]interface{}, 0)
	for _, val := range goodsIdsBySplitString {
		goodsIdsBySplitInterface = append(goodsIdsBySplitInterface, val)
	}
	update := make(map[string]interface{})
	update["number"] = number
	shoppingCart, args := sql_aid.PgTable(model.TableByUserShoppingCart).WhereIn("id", goodsIdsBySplitInterface...).Where("user_id = ?", userId).UpdateByMap(&update)
	_, err := model.PgSql.Exec(shoppingCart, args...)
	if err != nil {
		gogo_log.Error("server_UserShoppingCrtByEditNumber", "购物车商品数量失败", err.Error())
		return errors.New("更新失败")
	}
	return nil
}
